#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQmlComponent> // for load xml component
#include <QQuickItem>
#include <QQmlProperty>

#include "Page1Class.h" //include this page class

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    // Method 1: Register class object to QML
    // decalare
    Page1Class myPage1Class;

    // register myPage1Class to qml
    engine.rootContext()->setContextProperty("myPage1Class", &myPage1Class);

    // Method 2: Resister Class
    qmlRegisterType<Page1Class>("com.company.Page1Class", 1, 0, "Page1Class");

    // load main.qml
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(
        &engine, &QQmlApplicationEngine::objectCreated,
        &app, [url](QObject *obj, const QUrl &objUrl)
        {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1); },
        Qt::QueuedConnection);
    engine.load(url);

    // Method 3: load component----------------
    QQmlComponent component(&engine);
    component.loadUrl(QUrl(QString("qrc:/Window.qml")));
    QObject *qmlWindow = component.create();
    qmlWindow->setParent((engine.rootObjects().first()));
    engine.rootContext()->setContextProperty("qmlWindow", qmlWindow);

    //-----------------------

    QObject *rect = qmlWindow->findChild<QObject *>("myRectangle");
    if (rect)
    {
        qDebug() << "===myRectangle===:";
        rect->setProperty("color", "white");

        // change to QQuickItem
        QQuickItem *item = qobject_cast<QQuickItem *>(rect);
        item->setWidth(300);

        QQmlProperty(rect, "height").write(39);
    }

    //------------------------
    if (qmlWindow)
    {
        qDebug() << "===myWindow===:";
        qDebug() << "Property value read :" << QQmlProperty::read(qmlWindow, "myProperty").toString();
        QQmlProperty::write(qmlWindow, "myProperty", "Hello, Qt!");

        qDebug() << "Property value write:" << qmlWindow->property("myProperty").toString();
        qmlWindow->setProperty("myProperty", "Hello, QML!");
        qDebug() << "Property value write:" << qmlWindow->property("myProperty").toString();
    }
    //------------------------

    return app.exec();
}
